package com.janko.springbootbase.designmode.simpleFactory;

import java.util.HashMap;

/**
 * @Description 类文件说明
 * @Author nieyankang
 * @Version 1.0
 * @date {date} {time}
 */
public class HumanFactory  {
    /**
     * 创建指定的对象
     * @param c
     * @return
     */
    public  static Human createHuman(Class c){
        //工厂模式 延迟初始化
        HashMap<String,Human> mapHuman=new HashMap();

        Human human=null;
        try{
            if(mapHuman.containsKey(c.getSimpleName())){
                return  mapHuman.get(c.getSimpleName());
            }
            human=(Human)Class.forName(c.getName()).newInstance();
            mapHuman.put(c.getSimpleName(),human);
        } catch (IllegalAccessException e) {
//            e.printStackTrace();
            System.out.println("需要实现内部的方法，例如：必须指定人类的颜色");
        } catch (InstantiationException e) {
//            e.printStackTrace();
            System.out.println("定义的接口失败");
        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
            System.out.println("类加载失败~");
        }
        return human;
    }

    /**
     * 随机创建对象
     * @return
     */
    public static Human createHuman() {
        Human human = null; //定义一个类型的人类
        //首先是获得有多少个实现类，多少个人类
        java.util.List<Class> concreteHumanList = FactoryClassUtils.getAllClassByInterface(Human.class); //定义了多少人类
        //八卦炉自己开始想烧出什么人就什么人
        java.util.Random random = new java.util.Random();
        int rand = random.nextInt(concreteHumanList.size());
        human = createHuman(concreteHumanList.get(rand));
        return human;
    }
}

